package com.indusfo.spc.controller;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.exception.QueryFailedException;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.ProductLineService;
import com.indusfo.spc.service.RoleStationService;
import com.indusfo.spc.service.StationService;
import com.indusfo.spc.service.WorkshopService;
import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.CommonUtil;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工位前端控制层
 *
 * @author chenm
 * @create 2019-07-13 14:40
 */
@Controller
@RequestMapping("/service/station")
public class StationController {

    @Autowired
    private StationService stationService;

    @Resource
    private WorkshopService workShopService;

    @Autowired
    private ProductLineService productLineService;

    @Autowired
    private RoleStationService roleStationService;

    /**
     * 新增
     *
     * @param station
     * @return
     */
    @RequestMapping(value = "/insertStation", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject insertStation(Station station) {
        JSONObject json = stationService.insertStation(station);
        return json;

    }

    /**
     * 启用/停用
     *
     * @return com.indusfo.spc.vo.JSONObject
     * @author xuz
     * @date 2018/12/21 2:52 PM
     */
    @RequestMapping(value = "/definesStation", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject definesStation(Integer[] staIds, Integer dataState) {

        JSONObject json = stationService.delStation(staIds, dataState);
        return json;
    }

    /**
     * 更改
     *
     * @param station
     * @return
     */
    @RequestMapping(value = "/updateStation", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateStation(Station station) {

        JSONObject json = stationService.updateStation(station);
        return json;

    }

    /**
     * 查询
     *
     * @param station
     * @return
     */
    @RequestMapping(value = "/queryStation")
    @ResponseBody
    public JSONObject queryStation(Station station) {

        JSONObject json = stationService.queryStation(station);
        return json;

    }

    /**
     * 根据车间，产线，工序，查询工位集合
     *
     * @return
     */
    @RequestMapping(value = "/primary")
    @ResponseBody
    public JSONObject primary(Integer id, String name) {
        List<Station> liststStations = null;
        try {
            if ("production".equals(name)) {
                liststStations = stationService.getByProductionLineId(id);
            } else if (name.contentEquals("workshop")) {
                liststStations = stationService.getByWorkshopId(id);
            } else if ("pro".equals(name)) {
                liststStations = stationService.getByProId(id);
            } else {
                throw new QueryFailedException("输入参数有误");
            }

            if (liststStations.isEmpty()) {
                throw new QueryFailedException("没有产线相关数据");
            }
            //查询分页总记录数
            return JSONObject.oK(liststStations);
        } catch (GlobalException e) {
            return JSONObject.build(403, e.getMessage());
        }

    }

    /**
     * 车间，产线，工位三级树形结构
     *
     * @return
     */
    @RequestMapping(value = "/treeStation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONObject queryMouldTree() {
//        try {
//
//            List<XTreeNode> nodes = new ArrayList<>();
//            List<Workshop> workShops = workShopService.getList();
//            List<Productline> productLines = new ArrayList<Productline>();
//            if (null != workShops) {
//                for (Workshop workShop : workShops) {
//                    XTreeNode node = new XTreeNode();
//                    node.setId(workShop.getWorkshopId() + "W");
//                    node.setpId(null);
//                    node.setOpen(true);
//                    node.setFlag("chejian");
//                    node.setTitle(workShop.getWorkshopName());
//                    nodes.add(node);
//
//                    List<Productline> lines = productLineService.getByWorkshopId(workShop.getWorkshopId());
//                    productLines.addAll(lines);
//                }
//            }
//            List<Station> stations = new ArrayList<Station>();
//            for (Productline productline : productLines) {
//                XTreeNode node = new XTreeNode();
//                node.setId(productline.getProductlineId() + "P");
//                node.setpId(productline.getWorkshopId() + "W");
//                node.setOpen(true);
//                node.setFlag("canxian");
//                node.setTitle(productline.getProductlineName());
//                nodes.add(node);
//                List<Station> list = stationService.getByProductionLineId(productline.getProductlineId());
//                stations.addAll(list);
//            }
//            for (Station station : stations) {
//                XTreeNode node = new XTreeNode();
//                node.setId(station.getStationId() + "S");
//                node.setpId(station.getProductlineId() + "P");
//                node.setOpen(true);
//                node.setFlag("gongwei");
//                node.setTitle(station.getStationName());
//                nodes.add(node);
//            }
//            List<XTreeNode> tree = CommonUtil.getTree(nodes, null);
//            return JSONObject.oK(tree);
//        } catch (ParamsErrorException e) {
//            //返回封装异常信息的JSONObject给前端
//            return JSONObject.build(404, e.getMessage());
//        } catch (ModifyFailedException e) {
//            return JSONObject.build(404, e.getMessage());
//        }
        return stationService.treeStation();
    }

    /**
     * @author: louk
     * @Description:删除工序信息下的工位
     * @date: 2019/9/5 14:24
     */
    @RequestMapping(value = "/delStationByPro")
    @ResponseBody
    public JSONObject delStationByPro(Long[] staIds) {

        System.out.println(staIds);
        return stationService.delStationByPro(staIds);
    }

    /**
     * @Description Excel导入
     * @Author louk
     * @Date 11:08 2019/11/29
     */
    @RequestMapping("/uploadFileStation")
    @ResponseBody
    public JSONObject uploadFileStation(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {

        //定义一个JsonObject对象用于向前台传输数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.setStatus(JSONObject.SUCCESS);
        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            jsonObject.setStatus(JSONObject.ERROR);
            jsonObject.setMsg("文件解析错误");
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    jsonObject.setStatus(JSONObject.ERROR);
                    jsonObject.setMsg("未找到需要导入的数据，请确认表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
                } else {
                    List<Station> addProductPlans = new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        String staionCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                        String staionName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
                        String staType = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
                        String productionLineName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);
                        String remark = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 4, false);
                        Station plan = new Station(staionCode, staionName, staType, productionLineName, remark);
                        int m = i + 1;
                        //将excel中的每一行数据存储进行检查
                        String result = stationService.checkExcelContent(plan);
                        if (result != null) {
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
                            needAdd = false;
                        }
                        for (int j = 1; j < i; j++) {
                            //判断用户编码是否重复
                            String oldStaionCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false);
                            String oldStaionName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 1, false);
                            if (!StringUtils.isBlank(staionCode) && !StringUtils.isBlank(oldStaionCode) && oldStaionCode.equals(staionCode)) {
                                needAdd = false;
                                errorDatas.add(ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同工位编码"));
                            }
                            if (!StringUtils.isBlank(staionName) && !StringUtils.isBlank(oldStaionName) && oldStaionName.equals(staionName)) {
                                needAdd = false;
                                errorDatas.add(ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同工位名称"));
                            }
                        }
                        if (needAdd) {
                            addProductPlans.add(plan);
                        } else {
                            jsonObject.setStatus(JSONObject.ERROR);
                            jsonObject.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (jsonObject.getStatus().equals(JSONObject.ERROR) && !way) {
                        jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
                    } else {
                        if (addProductPlans.size() > 0) {
                            try {
                                stationService.updateListStation(addProductPlans);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                                if ("导入成功".equals(jsonObject.getMsg())) {
                                    jsonObject.setStatus(JSONObject.SUCCESS);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonObject.setMsg("导入失败");
                            }
                        }
                    }

                }
            }
        }
        jsonObject.setData(GsonUtil.toJson(errorDatas));
        return JSONObject.build(jsonObject.getStatus(), jsonObject.getMsg(), errorDatas);
    }


    @RequestMapping(value = "/role/treeStation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONObject roleStationTree(Integer roleId) {
        try {
            long start = System.currentTimeMillis();
            List<XTreeNode> nodes = new ArrayList<>();
            List<Workshop> workShops = workShopService.getList();
            List<Productline> productLines = new ArrayList<Productline>();
            if (null != workShops) {
                for (Workshop _workShop : workShops) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_workShop.getWorkshopId() + "W");
                    node.setpId(null);
                    node.setOpen(true);
                    node.setFlag("chejian");
                    node.setTitle(_workShop.getWorkshopName());
                    nodes.add(node);

                    List<Productline> lines = productLineService.getByWorkshopId(_workShop.getWorkshopId());
                    productLines.addAll(lines);
                }
            }
            List<Station> stations = new ArrayList<Station>();
            for (Productline _Line : productLines) {
                XTreeNode node = new XTreeNode();
                node.setId(_Line.getProductlineId() + "P");
                node.setpId(_Line.getWorkshopId() + "W");
                node.setOpen(true);
                node.setFlag("canxian");
                node.setTitle(_Line.getProductlineName());
                nodes.add(node);
                List<Station> list = stationService.getByProductionLineId(_Line.getProductlineId());
                stations.addAll(list);
            }
            List<RoleStation> roleStations = roleStationService.selectByRoleId(roleId);
            List<Integer> stationIds = roleStations.stream().map(RoleStation::getStationId).collect(Collectors.toList());
            for (Station _Station : stations) {
                XTreeNode node = new XTreeNode();
                node.setId(_Station.getStationId() + "S");
                node.setpId(_Station.getProductlineId() + "P");
                node.setOpen(true);
                node.setChecked(stationIds.contains(_Station.getStationId()));
                node.setFlag("gongwei");
                node.setTitle(_Station.getStationName());
                nodes.add(node);
            }
            List<XTreeNode> tree = CommonUtil.getTree(nodes, null);
            long end = System.currentTimeMillis();
            System.out.println(end-start);
            return JSONObject.oK(tree);
        } catch (ParamsErrorException e) {
            //返回封装异常信息的JSONObject给前端
            return JSONObject.build(404, e.getMessage());
        } catch (ModifyFailedException e) {
            return JSONObject.build(404, e.getMessage());
        }
    }

    /**
     * 去添加查询（产品，任务单，批次）
     */
    @RequestMapping(value = "/queryListStationToInsert")
    @ResponseBody
    public JSONObject queryListStationToInsert(Station station) {
        JSONObject json = stationService.queryListStationToInsert(station);
        return json;
    }
}
